// const dsbridge = require("./dsbridge.js");
import dsbridge from "./dsbridge.js";
// import store from '../store/index.js'; // yuanbin 20240514 暂时注释掉， 后续如果需要判断权限则取消注释

const appUtil = {
	// 下载视频
	 downloadVideo  (url)  {
		uni.showLoading({
			title: "下载到相册中",
			mask: true,
		})
		// 1.将远程文件下载到小程序的内存中,tempFilePath
		uni.downloadFile({
			url,
			success: (res) => {
				console.log("res", res)

				uni.saveVideoToPhotosAlbum({
					filePath: res.tempFilePath,
					success: () => {
						setTimeout(() => {
							uni.showToast({
								title: "下载成功",
							})
						}, 500);
					},
					// 拒绝授权等情况
					fail: (fail) => {
						if (
							fail.errMsg === "saveVideoToPhotosAlbum:fail auth deny" ||
							fail.errMsg === "saveVideoToPhotosAlbum:fail auth denied" ||
							fail.errMsg === "saveVideoToPhotosAlbum:fail authorize no response"
						) {
							uni.showModal({
								title: "提示",
								content: "需要您授权保存相册",
								success: function (res) {
									if (res.confirm) {
										uni.openSetting({
											success(settingdata) {
												if (settingdata.authSetting["scope.writePhotosAlbum"]) {
													uni.showModal({
														title: "提示",
														content: "获取权限成功,再次点击下载视频即可保存",
													})
												} else {
													uni.showModal({
														title: "提示",
														content: "获取权限失败,将无法保存到相册哦",
													})
												}
											},
											fail(failData) {},
											complete(finishData) {},
										})
									} else if (res.cancel) {
										console.log("用户点击取消")
									}
								},
							})
						}
					},
					complete: (res) => {
						console.log(res)

						uni.hideLoading()
					},
				})
			},
		})
	},
	/* 通过创建时间获取进度 */
	videoCompositionProgress  (date) {
		const curDate = new Date().getTime()
		const gmtCreate = new Date(date).getTime()
		const t = Math.round((curDate - gmtCreate) / 1000)
		const processPercent = Math.min(Math.floor(Number((t / 150) * 100)), 90)
		return processPercent
	},

	//  秒数转化为时分秒
	formatSeconds:function(value) {
		// 转换为式分秒
		let h = parseInt(((value / 60 / 60) % 24) + "")
		h = h < 10 ? "0" + h : h
		let m = parseInt(((value / 60) % 60) + "")
		m = m < 10 ? "0" + m : m
		let s = parseInt((value % 60) + "")
		s = s < 10 ? "0" + s : s
		// 作为返回值返回
		return m + ":" + s
	},
	// 格式化 成金额格式的字符串
	formattedAmountString: function formattedAmountString(params) {
		const value = Number(params);
		const result = value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
		return result;
	},
	// 计算两个经纬度位置的距离s
	distanceFromLocation: function name(params1, params2) {
		let latitude1 = params1.latitude;
		let longitude1 = params1.longitude;
		let latitude2 = params2.latitude;
		let longitude2 = params2.longitude;
		var a = Number(latitude1) - Number(latitude2);
		var b = Number(longitude1) - Number(longitude2);
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * 6378.137; // EARTH_RADIUS;

		s = Math.round(s * 10000) / 10000; //输出为公里
		// var distance = s;
		// var distance_str = "";
		// if (parseInt(distance) >= 1) {
		//   distance_str = distance.toFixed(1) + "km";
		// } else {
		//   distance_str = distance * 1000 + "m";
		// }

		return s;
	},

	getAccountInfoSync: function () {
		// #ifdef H5
		return {
			miniProgram: {
				/**
				 * 小程序 appId
				 */
				appId: 'appId',
				/**
				 * 小程序版本
				 *
				 * 可选值：
				 * - 'develop': 开发版;
				 * - 'trial': 体验版;
				 * - 'release': 正式版;
				 *
				 * 最低基础库： `2.10.0`
				 */
				envVersion: '',
				/**
				 * 线上小程序版本号
				 *
				 * 最低基础库： `2.10.2`
				 */
				version: 'App.version',
			},
			plugin: {
				/**
				 * 插件 appId
				 */
				appId: '00000',
				/**
				 * 插件版本号
				 */
				version: '000000',
			},
		}
		// #endif

		// #ifdef MP-WEIXIN
		return uni.getAccountInfoSync();
		// #endif
	},
	needLogin: function (callback) {
		if (dsbridge.isRunOnPhone) {
			///运行在手机环境
			dsbridge.needLogin()
		} else {
			///小程序环境
			// yuanbin 20240514 暂时注释掉， 后续如果需要判断权限则取消注释
			// if (!this.isLogin() && !store.$state.isLoginIng) {
			// 	store.commit('SET_lOGIN',true);
			// 	uni.showToast({
			// 		title: '请先登录',
			// 		duration: 1000,
			// 		icon: "none"
			// 	})
			// 	setTimeout(() => {
			// 		uni.navigateTo({
			// 			url: '/commonSubPack/pages/login/index'
			// 		})
			// 	}, 1000)
			// }
		}
	},
	/* 是否登录状态 */
	isLogin: function () {
		if (dsbridge.isRunOnPhone) {
			///运行在手机环境
			return dsbridge.isLogin()
		} else {
			// yuanbin 20240514 暂时注释掉， 后续如果需要判断权限则取消注释
			// const token = store.$state.Authentication 
			// const openid = uni.getStorageSync('openid')
			// return token !== undefined && token !== "" && openid !== undefined && openid !== ""
		}
	},
	/* 拨打电话 */
	makePhoneCall: function (phone) {
		if (dsbridge.isRunOnPhone) {
			///运行在手机环境
			dsbridge.makePhoneCall(phone)
		} else {
			uni.makePhoneCall({
				phoneNumber: phone,
			});
		}
	},
	interceptorNavigateRedirectTo: function (value) {
		let currentRoutes = getCurrentPages()
		let hidden = currentRoutes.length >= 1
		dsbridge2.setTabBarIsHiden(hidden)
	}, interceptorNavigateBack: function (value) {
		//在安卓中，获取不到value.delta即返回多少层，设置默认值1层
		let currentRoutes = getCurrentPages()
		///可能不止返回一级   当前路由深度 - 返回深度 = 剩余深度
		let hidden = currentRoutes.length - (value.delta ?? 1) > 1
		dsbridge2.setTabBarIsHiden(hidden)
	}
};
export default appUtil;